package es.unileon.prg2.censo.handler;

/**
 * @author Manuel Molinos Crespo, Adrian Campazas Vega, Alberto Castro Delgado, Pedro Alvarez Alvarez, Adrian Cabello Galvan, Jose Alvaro Fernandez Alvarez
 *
 */


import es.unileon.prg2.censo.exception.CensoException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class DNICitizen implements Handler {
	static Logger logger = Logger.getLogger(DNICitizen.class.getName());
	private String id;
	
	/**
	 * Constructor used for created the ID of the citizen.
	 * @param id String composite for 8 numbers and 1 letter
	 * @throws CensoException
	 */
	public DNICitizen (String id) throws CensoException{
		StringBuffer message = new StringBuffer();
		PropertyConfigurator.configure("etc/log4j.properties");
		if (id.length() == 8){ //add 0 in 'id' by left when number of characters is eight
			id = "0"+id;
		logger.info("add 0 in 'id' by left when number of characters is eight");
		}
		
		if (id.length() !=9){
			message.append("The length of the identifier should be 8 or 9. "+id+" is not valid.\n");
			logger.error("The length of the identifier should be 8 or 9");
		} else{
			for (int i=0;i<id.length()-1;i++){
				if(Character.isLetter(id.charAt(i))){
					message.append("the first seven or eight character should be numbers. "+id+" is not vail.\n");
				logger.error("the first seven or eight character should be numbers.");
				}
			}
		}
		
		if (id.length() == 0){
			message.append("The identifier can not be an empty one.\n");
			logger.error("The identifier can not be an empty one.\n");
		}
		
		
		
		
		if(message.length()!=0){
			throw new CensoException(message.toString());
		}else{
			this.id=id;
			logger.info(id+ " created successfully");
		}
	}
	
	/**
	 * Other constructor used for created the ID of the citizen from a Handler parameter.
	 * @param id Handler composite for 8 numbers and 1 letter
	 * @throws CensoException
	 */
	public DNICitizen(Handler id) throws CensoException {
		this(id.toString());
	}

	@Override
	public int compareTo(Handler another) {
		return this.id.compareTo(another.toString());
	}
	
	@Override
	public String toString()
	{
		return id;
	}

}
